"""LeadTag model - Lead与Tag的多对多关联表."""

from __future__ import annotations

from typing import TYPE_CHECKING

from sqlalchemy import Integer, Float, String, ForeignKey, Index
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from ..models.base import TimestampMixin

if TYPE_CHECKING:
    from ..models.lead import Lead
    from ..models.tag import Tag


class TagSource(str):
    """标签来源."""

    AI = "ai"  # AI自动提取
    RULE = "rule"  # 规则引擎匹配
    MANUAL = "manual"  # 人工添加


class LeadTag(Base, TimestampMixin):
    """Lead标签关联表 - 多对多关系 + 元数据.

    存储Lead和Tag的关联关系，以及AI提取的元数据：
    - confidence: AI置信度（0.0-1.0）
    - source: 标签来源（ai/rule/manual）
    - created_at: 添加时间

    索引：
    - (lead_id, tag_id): 复合唯一索引
    - (tag_id): 反向查询优化
    - (confidence): 按置信度排序
    """

    __tablename__ = "lead_tags"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)

    # 关联关系
    lead_id: Mapped[int] = mapped_column(
        ForeignKey("leads.id", ondelete="CASCADE"), nullable=False, index=True, comment="客户ID"
    )

    tag_id: Mapped[int] = mapped_column(
        ForeignKey("tags.id", ondelete="CASCADE"), nullable=False, index=True, comment="标签ID"
    )

    # AI元数据
    confidence: Mapped[float] = mapped_column(
        Float, nullable=False, default=1.0, index=True, comment="置信度（0.0-1.0），AI提取时有效"
    )

    source: Mapped[str] = mapped_column(
        String(20),
        nullable=False,
        default=TagSource.MANUAL,
        index=True,
        comment="标签来源：ai/rule/manual",
    )

    # Relationships
    lead: Mapped[Lead] = relationship("Lead", back_populates="lead_tags")
    tag: Mapped[Tag] = relationship("Tag", back_populates="lead_tags")

    # 复合唯一索引：一个Lead不能有重复的Tag
    __table_args__ = (Index("ix_lead_tag_unique", "lead_id", "tag_id", unique=True),)

    def __repr__(self) -> str:
        return f"<LeadTag(lead_id={self.lead_id}, tag_id={self.tag_id}, source='{self.source}', confidence={self.confidence:.2f})>"
